package com.yh.filter;

import com.yh.dao.common.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

import javax.servlet.*;
import java.io.IOException;

public class OpenSessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Session session=null;
        Transaction tr=null;
        try {
            session= HibernateUtil.currentSession();
            tr= session.beginTransaction();
            filterChain.doFilter(servletRequest,servletResponse);
           tr.commit();
       }
       catch (Exception ex)
       {
           tr.rollback();
           //log4j记录错误日志
           ex.printStackTrace();
       }
       finally{
            HibernateUtil.closeSession();
        }
    }

    @Override
    public void destroy() {

    }
}
